package com.example.luyao.faceservertest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private final static String TAG = MainActivity.class.getCanonicalName();
    private int timeout = 30;
    private Thread thread_test;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        thread_test = new RecognitionThread();
        thread_test.start();
    }

    public class RecognitionThread extends Thread {
        RecognitionThread() {
            super();
        }

        @Override
        public void run() {
            super.run();
            try {
                for(int i = 0; i < 12; i++) {
                    //test_register_user();
                    //test_recognition_user();
                    //test_recognition_user_1();
                    test_update_user_info();
                    //test_delete_user();
                    //test_get_all_user();
                    Thread.sleep(3000);
                }
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }

        private int test_register_user() {
            long startTime = System.currentTimeMillis();
            SimpleHttpClient.ServerAPI service = Utils.getHttpClient(timeout);
            String user_id = "e10adc3949ba59abbe56e057f20f883e";
            String remark = "test";
            String name = "李四";

            File image_file = new File("/sdcard/A/1.jpg");
            if (!image_file.exists()) return 0;
            byte[] image_data = new byte[(int) image_file.length()];
            try {
                BufferedInputStream buf = new BufferedInputStream(new FileInputStream(image_file));
                buf.read(image_data, 0, image_data.length);
                buf.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), image_data);

            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("image", "img.jpg", requestFile)
                    .build();
            String url = SimpleHttpClient.BASE_URL + "/register_user";
            url += "?user_id=" + user_id + "&remark=" + remark + "&name=" + name;
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            okhttp3.Call call = client.newCall(request);
            call.enqueue(new okhttp3.Callback() {
                @Override
                public void onResponse(okhttp3.Call call, okhttp3.Response response) {
                    JSONObject responseJson = Utils.parseOkhttp3Response(response, TAG);
                    if (response.code() == 200) {
                        Log.e(TAG, "test_register_user " + responseJson.toString());
                    } else {
                        //toast("连接网络失败，请稍后再试");
                        Log.e(TAG, "test_register_user " + responseJson.toString());
                    }
                    Log.e(TAG, "test_register_user spend " + (System.currentTimeMillis() - startTime));
                }

                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    toast("连接网络失败，请检查您的网络");
                    e.printStackTrace();
                }
            });
            return 0;
        }

        private int test_recognition_user() {
            long startTime = System.currentTimeMillis();
            SimpleHttpClient.ServerAPI service = Utils.getHttpClient(timeout);
            File image_file = new File("/sdcard/A/1.jpg");
            byte[] image_data = new byte[(int) image_file.length()];
            try {
                BufferedInputStream buf = new BufferedInputStream(new FileInputStream(image_file));
                buf.read(image_data, 0, image_data.length);
                buf.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), image_data);

            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", "img.jpg", requestFile)
                .build();
            Request request = new Request.Builder()
                .url(SimpleHttpClient.BASE_URL + "/recognition_user")
                .post(requestBody)
                .build();
            okhttp3.Call call = client.newCall(request);
            call.enqueue(new okhttp3.Callback() {
                    @Override
                    public void onResponse(okhttp3.Call call, okhttp3.Response response) {
                        JSONObject responseJson = Utils.parseOkhttp3Response(response, TAG);
                        if (response.code() == 200) {
                            Log.e(TAG, "test_recognition_user " + responseJson.toString());
                        } else {
                            //toast("连接网络失败，请稍后再试");
                            Log.e(TAG, "test_recognition_user " + responseJson.toString());
                        }
                        Log.e(TAG, "test_recognition_user spend " + (System.currentTimeMillis() - startTime));
                    }

                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {
                        toast("连接网络失败，请检查您的网络");
                        e.printStackTrace();
                    }
                });
            return 0;
        }

        private int test_recognition_user_1() {
            long startTime = System.currentTimeMillis();
            SimpleHttpClient.ServerAPI service = Utils.getHttpClient(timeout);
            File image_file = new File("/sdcard/A/1.jpg");
            byte[] image_data = new byte[(int) image_file.length()];
            try {
                BufferedInputStream buf = new BufferedInputStream(new FileInputStream(image_file));
                buf.read(image_data, 0, image_data.length);
                buf.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), image_data);
            MultipartBody.Part image = MultipartBody.Part.createFormData(
                "image", "img.jpg", requestFile);
            Call<ResponseBody> call = service.recognition_user(image);
            call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        JSONObject responseJson = Utils.parseResponse(response, TAG);
                        if (response.code() == 200) {
                            Log.e(TAG, "test_recognition_user " + responseJson.toString());
                        } else {
                            //toast("连接网络失败，请稍后再试");
                            Log.e(TAG, "test_recognition_user " + responseJson.toString());
                        }
                        Log.e(TAG, "test_recognition_user_1 spend " + (System.currentTimeMillis() - startTime));
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        toast("连接网络失败，请检查您的网络");
                        t.printStackTrace();
                    }
                });

            return 0;
        }

        private int test_update_user_info() {
            long startTime = System.currentTimeMillis();

            SimpleHttpClient.ServerAPI service = Utils.getHttpClient(timeout);
            int feature_id = 3;
            String user_id = "e10adc3949ba59abbe56e057f20f883e";
            String remark = "test";
            String name = "李四";

            File image_file = new File("/sdcard/A/1.jpg");
            byte[] image_data = new byte[(int) image_file.length()];
            try {
                BufferedInputStream buf = new BufferedInputStream(new FileInputStream(image_file));
                buf.read(image_data, 0, image_data.length);
                buf.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), image_data);
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("image", "img.jpg", requestFile)
                    .build();
            String url = SimpleHttpClient.BASE_URL + "/update_user_info";
            url += "?user_id=" + user_id + "&remark=" + remark + "&name=" + name + "&feature_id=" + feature_id;
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            okhttp3.Call call = client.newCall(request);
            call.enqueue(new okhttp3.Callback() {
                @Override
                public void onResponse(okhttp3.Call call, okhttp3.Response response) {
                    JSONObject responseJson = Utils.parseOkhttp3Response(response, TAG);
                    if (response.code() == 200) {
                        Log.e(TAG, "test_update_user_info " + responseJson.toString());
                    } else {
                        //toast("连接网络失败，请稍后再试");
                        Log.e(TAG, "test_update_user_info " + responseJson.toString());
                    }
                    Log.e(TAG, "test_update_user_info spend " + (System.currentTimeMillis() - startTime));
                }

                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    toast("连接网络失败，请检查您的网络");
                    e.printStackTrace();
                }
            });
            return 0;
        }

        private int test_delete_user() {
            SimpleHttpClient.ServerAPI service = Utils.getHttpClient(timeout);
            int feature_id = 2;
            Call<ResponseBody> call = service.delete_user(feature_id);
            call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        JSONObject responseJson = Utils.parseResponse(response, TAG);
                        if (response.code() == 200) {
                            Log.e(TAG, "test_delete_user " + responseJson.toString());
                        } else {
                            //toast("连接网络失败，请稍后再试");
                            Log.e(TAG, "test_delete_user " + responseJson.toString());
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        toast("连接网络失败，请检查您的网络");
                        t.printStackTrace();
                    }
                });
            return 0;
        }

        private int test_get_all_user() {
            long startTime = System.currentTimeMillis();
            SimpleHttpClient.ServerAPI service = Utils.getHttpClient(timeout);
            Call<ResponseBody> call = service.get_all_user();
            call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        JSONObject responseJson = Utils.parseResponse(response, TAG);
                        if (response.code() == 200) {
                            Log.e(TAG, "test_get_all_user " + responseJson.toString());
                        } else {
                            //toast("连接网络失败，请稍后再试");
                            Log.e(TAG, "test_get_all_user " + responseJson.toString());
                        }
                        Log.e(TAG, "test_get_all_user spend " + (System.currentTimeMillis() - startTime));
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        toast("连接网络失败，请检查您的网络");
                        t.printStackTrace();
                    }
                });
            return 0;
        }

    }

    @Override
    protected void onDestroy() {
        Log.e(TAG, "lifecycle: onDestroy");
        try {
            thread_test.join();
        } catch (InterruptedException e){
            e.printStackTrace();
        }
        super.onDestroy();
    }

    protected void toast(final String msg) {
        runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }
            });
    }
}
